//
//  NSString+Utility.m
//  Utility
//
//  Created by Robin on 7/5/16.
//  Copyright © 2016 Robin. All rights reserved.
//

#import "NSString+Utility.h"

@implementation NSString (Utility)

- (NSString *)stringByTrimingWhitespace {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (BOOL)isPureInt {
    NSScanner* scan = [NSScanner scannerWithString:self];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

#pragma mark - JSON vs Object -
+ (NSString *)jsonStringWithObject:(id)object {
    NSError *error;
    
    if (object) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
        
        if (!error) {
            
            NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            
            return jsonString;
        }
    }
    
    return nil;
}

+ (id)objectWithJsonString:(NSString *)jsonString {
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments error:&error];
    
    if (!error) {
        
        return jsonObject;
    }
    
    return nil;
}

- (CGSize)calSizeWithSpecifiedFontSize:(NSInteger)fntSize AndWidth:(CGFloat)width {
    if (self == nil) {
        return CGSizeZero;
    }
    
    CGRect rect = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fntSize]} context:nil];
    return rect.size;
}

/**
 *  转义url包含中文 空格等一些特殊的字符
 *
 *  @param urlContainSpecialChar 包含中文 空格等一些特殊的字符
 *
 *  @return 可以生成NSURL的NSString
 */
- (NSString *)convertToUrlEncoding:(NSString *)urlContainSpecialChar {
    if (urlContainSpecialChar) {
        return nil;
    }
    
    NSString * urlString = [urlContainSpecialChar stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "]];
    
    return urlString;
}

@end
